package xyz.wanwanwan.www.hrm.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.wanwanwan.www.hrm.constant.CodeConstant;
import xyz.wanwanwan.www.hrm.domain.Sso;
import xyz.wanwanwan.www.hrm.dto.SMSCodeDto;
import xyz.wanwanwan.www.hrm.feign.client.CacheFeign;
import xyz.wanwanwan.www.hrm.mapper.SsoMapper;
import xyz.wanwanwan.www.hrm.service.IVerifycodeService;
import xyz.wanwanwan.www.hrm.util.AjaxResult;
import xyz.wanwanwan.www.hrm.util.SendMessageCode;
import xyz.wanwanwan.www.hrm.util.StrUtils;
import xyz.wanwanwan.www.hrm.util.VerifyCodeUtils;

import java.io.IOException;

@Service
@Slf4j
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private SsoMapper ssoMapper;
    @Autowired
    private CacheFeign cacheFeign;
    @Override
    public String getImageCode(String imageCodeKey) throws IOException {
        //判断前端key值是否到位
        if(StringUtils.isEmpty(imageCodeKey)){
            throw new RuntimeException("网络异常，请刷新重试！！！！！！");
        }
        String randomString=null;
        //根据key值查询redis是否有值
        AjaxResult fromRedis = cacheFeign.getFromRedis(imageCodeKey);
        if(fromRedis.isSuccess()){
            randomString=fromRedis.getResultObj().toString();
        }else{
            //创建随机值
            randomString = StrUtils.getComplexRandomString(4);
        }
        //将数值存入redis
        AjaxResult ajaxResult = cacheFeign.setImageCodeToRedis(imageCodeKey,600,
                randomString);
        if(!ajaxResult.isSuccess()){
            throw new RuntimeException("网络异常，请刷新重试！！！！！！");
        }
        //通过BASE64将随机值合并到图片中用输出流以string字符串返回
        return VerifyCodeUtils.MyVerifyCode(140,40,randomString);
    }

    /**
     * 发送短信验证码
     * @param smsCodeDto
     * @return
     */
    @Override
    public AjaxResult sendSmsCode(SMSCodeDto smsCodeDto) {
        if(StringUtils.isEmpty(smsCodeDto.getMobile())){
            throw new RuntimeException("电话号码不能为空");
        }
        if(StringUtils.isEmpty(smsCodeDto.getImageCodeKey())){
            throw new RuntimeException("网络繁忙,请刷新");
        }
        if(StringUtils.isEmpty(smsCodeDto.getImageCode())){
            throw new RuntimeException("验证码不能为空");
        }
        //通过key值获取图形验证码
        AjaxResult fromRedis = cacheFeign.getFromRedis(smsCodeDto.getImageCodeKey());
        //判断验证码是否过期
        if(fromRedis.isSuccess()){
            //判断图形验证码是否正确
          if(smsCodeDto.getImageCode().toUpperCase().equals(fromRedis.getResultObj().toString().toUpperCase())){
              //发送手机验证码
              sendPhoneCode(smsCodeDto.getMobile());
          }
        }else {
            return AjaxResult.me().setSuccess(false).setMessage("图形验证码不正确");
        }
        return AjaxResult.me();
    }

    /**
     * 获取手机验证码
     * @param phone
     * @return
     */
    public AjaxResult sendPhoneCode(String phone){
        //从redis获取验证码
        String resultObj = cacheFeign.getFromRedis(CodeConstant.PHONE_CODE_KEY + ":" + phone).getResultObj().toString();
        //随机短信验证码
        String code = StrUtils.getComplexRandomString(6);
        //判断验证码是否过期
        if(StringUtils.isNotEmpty(resultObj)){
            //获取前一次发送时间戳
            long beforeTime = Long.valueOf(resultObj.split(",")[1]);
            //获取当前时间
            long now = System.currentTimeMillis();
            if(now-beforeTime<60*1000){
                return AjaxResult.me().setSuccess(false).setMessage("请不要在一分钟内多次发送");
            }
            //没有过期则返回当前验证码
            code = resultObj.split(",")[0];
        }
        //如果验证码已过期则新创建验证码并存入redis
        AjaxResult ajaxResult = cacheFeign.setImageCodeToRedis(CodeConstant.PHONE_CODE_KEY + ":" + phone, 30*6000,code + "," + System.currentTimeMillis());
        if(!ajaxResult.isSuccess()){
            log.error("短信验证码存入redis失败");
            throw new RuntimeException("短信验证码已过期");
        }
        String text = "尊敬的用户，你的验证码是："+code+"请在5分钟内操作完成";
       // SendMessageCode.sendPhoneCode(phone,text);
        log.error("验证码"+code);
        return AjaxResult.me();
    }
}
